package com.lzx.iteam.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.lzx.iteam.R;
import com.lzx.iteam.bean.EventListData;
import com.lzx.iteam.emotion.gif.AnimatedGifDrawable;
import com.lzx.iteam.emotion.gif.AnimatedImageSpan;
import com.lzx.iteam.widget.gridimg.MyGridView;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.DateUtil;
import com.lzx.iteam.util.StringUtil;
import io.rong.imageloader.core.listener.ImageLoadingListener;
import io.rong.imageloader.core.listener.SimpleImageLoadingListener;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by shijunting on 15-5-19.
 */
public class EventsListAdapter extends BaseAdapter {

    private ArrayList<EventListData> eventsListDatas = new ArrayList<EventListData>();
    private Context mContext;
    private final int TYPE_EVENT = 0;
    private final int TYPE_ACTIVITY = 1;
    private final int TYPE_VOTE = 2;
    private final int TYPE_REG = 3;
    private ImageLoadingListener animateFirstListener;
    private ViewHolder holder = null;
    private ArrayList<String> mImages;
    private EventImageAdapter mImageAdapter;

    public EventsListAdapter(Context context) {
        this.eventsListDatas.clear();
        this.mContext = context;
        animateFirstListener = new AnimateFirstDisplayListener();
    }

    public void setData(ArrayList<EventListData> eventsListDatas) {
        this.eventsListDatas.clear();
        this.eventsListDatas.addAll(eventsListDatas);
        notifyDataSetChanged();
        Log.d("Event_UpDate", "notifyDataSetChanged");
    }

    public ArrayList<EventListData> getData() {
        return eventsListDatas;
    }

    @Override
    public int getCount() {
        return eventsListDatas==null?0:eventsListDatas.size();
    }

    @Override
    public Object getItem(int position) {
        return eventsListDatas==null?null:eventsListDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        if ("7".equals(eventsListDatas.get(position).getEventType())) {
            return TYPE_ACTIVITY;
        } else if ("8".equals(eventsListDatas.get(position).getEventType())) {
            return TYPE_VOTE;
        }else if ("9".equals(eventsListDatas.get(position).getEventType())) {
            return TYPE_REG;
        }else {
            return TYPE_EVENT;
        }
    }

    @Override
    public int getViewTypeCount() {
        return 4;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final EventListData eventData = eventsListDatas.get(position);
        int type = getItemViewType(position);
        if (convertView == null) {
            holder = new ViewHolder();
            switch (type) {
                case TYPE_EVENT:
                    convertView = LayoutInflater.from(mContext).inflate(R.layout.event_list_event_item, null);
                    holder.event_title = (TextView) convertView.findViewById(R.id.tv_event_title);
                    holder.event_content = (TextView) convertView.findViewById(R.id.tv_event_content);
                    holder.event_time = (TextView) convertView.findViewById(R.id.tv_event_update_time);
                    holder.event_img = (ImageView) convertView.findViewById(R.id.iv_event_img);
                    holder.event_new_msg = (ImageView) convertView.findViewById(R.id.iv_event_red_new);
                    holder.event_reply = (TextView) convertView.findViewById(R.id.tv_event_reply);
                    holder.event_reply_count = (TextView) convertView.findViewById(R.id.tv_event_reply_count);
                    holder.event_reply_layout = (RelativeLayout) convertView.findViewById(R.id.rl_event_reply_layout);
                    holder.event_reply_count_layout = (LinearLayout) convertView.findViewById(R.id.ll_event_reply_count_layout);
                    holder.event_image_layout=(LinearLayout)convertView.findViewById(R.id.ll_event_image_layout);
                    holder.event_image_count=(TextView)convertView.findViewById(R.id.tv_event_image_count);
                    holder.mGvImageGrid = (MyGridView) convertView.findViewById(R.id.event_list_item_gv_image);
                    convertView.setTag(holder);
                    break;
                case TYPE_ACTIVITY:
                    convertView = LayoutInflater.from(mContext).inflate(R.layout.event_list_activity_item, null);
                    holder.event_title = (TextView) convertView.findViewById(R.id.tv_event_title);
                    holder.event_content = (TextView) convertView.findViewById(R.id.tv_event_content);
                    holder.event_time = (TextView) convertView.findViewById(R.id.tv_event_update_time);
                    holder.event_img = (ImageView) convertView.findViewById(R.id.iv_event_img);
                    holder.event_new_msg = (ImageView) convertView.findViewById(R.id.iv_event_red_new);
                    holder.event_activity_time = (TextView) convertView.findViewById(R.id.tv_event_activity_time);
                    holder.event_activity_site = (TextView) convertView.findViewById(R.id.tv_event_activity_address);
                    holder.event_image_layout=(LinearLayout)convertView.findViewById(R.id.ll_event_image_layout);
                    holder.event_image_count=(TextView)convertView.findViewById(R.id.tv_event_image_count);
                    holder.mGvImageGrid = (MyGridView) convertView.findViewById(R.id.event_list_item_gv_image);
                    convertView.setTag(holder);
                    break;
                case TYPE_VOTE:
                    convertView = LayoutInflater.from(mContext).inflate(R.layout.event_list_vote_item, null);
                    holder.event_title = (TextView) convertView.findViewById(R.id.tv_event_title);
                    holder.event_ll_layout = (LinearLayout) convertView.findViewById(R.id.ll_event_votes);
                    holder.event_time = (TextView) convertView.findViewById(R.id.tv_event_update_time);
                    holder.event_img = (ImageView) convertView.findViewById(R.id.iv_event_img);
                    holder.event_new_msg = (ImageView) convertView.findViewById(R.id.iv_event_red_new);
                    holder.event_image_layout=(LinearLayout)convertView.findViewById(R.id.ll_event_image_layout);
                    holder.event_image_count=(TextView)convertView.findViewById(R.id.tv_event_image_count);
                    holder.mGvImageGrid = (MyGridView) convertView.findViewById(R.id.event_list_item_gv_image);
                    convertView.setTag(holder);
                    break;
                case TYPE_REG:
                    convertView = LayoutInflater.from(mContext).inflate(R.layout.event_list_reg_item, null);
                    holder.event_title = (TextView) convertView.findViewById(R.id.tv_event_title);
                    holder.event_content = (TextView) convertView.findViewById(R.id.tv_event_content);
                    holder.event_time = (TextView) convertView.findViewById(R.id.tv_event_update_time);
                    holder.event_ll_note = (LinearLayout) convertView.findViewById(R.id.ll_event_note);
                    holder.event_img = (ImageView) convertView.findViewById(R.id.iv_event_img);
                    holder.event_new_msg = (ImageView) convertView.findViewById(R.id.iv_event_red_new);
                    holder.event_image_layout=(LinearLayout)convertView.findViewById(R.id.ll_event_image_layout);
                    holder.event_activity_time = (TextView) convertView.findViewById(R.id.tv_event_reg_time);
                    holder.event_activity_site = (TextView) convertView.findViewById(R.id.tv_event_reg_address);
                    convertView.setTag(holder);
                    break;
            }

        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if(eventData.getUpdateTime()!=null){
        holder.event_time.setText(DateUtil.getChatTime(Long.parseLong(eventData.getUpdateTime()) * 1000));}
        if (!StringUtil.isEmpty(eventData.getEventTitle())) {
            holder.event_title.setText(eventData.getEventTitle());
        } else {
            if ("1".equals(eventData.getUserType())) {
                holder.event_title.setText("发起一份" + eventData.getEventName());
            } else {
                holder.event_title.setText("发给您一份" + eventData.getEventName());
            }
        }
        if (!"8".equals(eventData.getEventType())){
            if (!StringUtil.isEmpty(eventData.getInitTitle3())) {
                StringBuilder content = new StringBuilder();
                content.append(eventData.getContent1()).append(eventData.getContent2()).append(eventData.getContent3());
                holder.event_content.setText(content);

            } else if (!StringUtil.isEmpty(eventData.getInitTitle2())) {
                StringBuilder content = new StringBuilder();
                content.append(eventData.getContent1()).append(eventData.getContent2());
                holder.event_content.setText(content);
            } else if(!StringUtil.isEmpty(eventData.getContent1())){
                holder.event_content.setText(eventData.getContent1());
            }
            if ("0".equals(eventData.getHasRead())) {
                holder.event_new_msg.setVisibility(View.VISIBLE);
            } else {
                holder.event_new_msg.setVisibility(View.GONE);
            }
        }

        if(!StringUtil.isEmpty(eventData.getThumbImage())){
            holder.event_image_layout.setVisibility(View.VISIBLE);
            final String[] image = eventData.getThumbImage().split(",");

            if (image.length > 0){
                String[] images = eventData.getOriImage().split(",");
                mImages = new ArrayList<String>();
                for (int i = 0;i < images.length;i++){
                    mImages.add(images[i]);
                }
                if(image.length > 3){
                    String[] newImage = {image[0],image[1],image[2]};
                    mImageAdapter = new EventImageAdapter(mContext,newImage,mImages,eventData.getThumbImage(),eventData.getEventId());
                }else{
                    mImageAdapter = new EventImageAdapter(mContext,image,mImages,eventData.getThumbImage(),eventData.getEventId());
                }
                holder.mGvImageGrid.setAdapter(mImageAdapter);
                // 防止Item不可点击
                holder.mGvImageGrid.setEnabled(false);
                holder.mGvImageGrid.setClickable(false);
            }

            /*holder.mGvImageGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                    String[] images = eventData.getOriImage().split(",");
                    Intent intent = new Intent(mContext, ImagePagerActivity.class);
                    intent.putExtra(Constants.IMAGE_ORIGIN, Constants.IMAGE_ORIGIN_URL_ARRAY);
                    mImages = new ArrayList<String>();
                    for (int i = 0;i < images.length;i++){
                        mImages.add(images[i]);
                    }
                    intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS,mImages);
                    intent.putExtra(ImagePagerActivity.EXTRA_THUME_IMAGES,eventData.getThumbImage());
                    intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
                    mContext.startActivity(intent);
                }
            });*/

            holder.event_image_count.setText("共"+image.length+"张图片");

        }else{
            holder.event_image_layout.setVisibility(View.GONE);
        }
        switch (type) {
            case TYPE_EVENT:
                holder.event_reply_layout.setVisibility(View.GONE);
                if ("1".equals(eventData.getEventType())) {//公告
                    holder.event_img.setImageDrawable(mContext.getResources().getDrawable(R.drawable.gonggao_img));
                } else if ("4".equals(eventData.getEventType())) {//普通事件
                    holder.event_img.setImageDrawable(mContext.getResources().getDrawable(R.drawable.event_img));
                    if (StringUtil.isEmpty(eventData.getReplyLastName())) {//无回复
                        holder.event_reply_layout.setVisibility(View.GONE);
                    } else {//有回复
                        holder.event_reply_layout.setVisibility(View.VISIBLE);
                        SpannableStringBuilder sb = handler(holder.event_reply,
                                eventData.getReplyLastContent());
                        holder.event_reply.setText(eventData.getReplyLastName() + ":");
                        holder.event_reply.append(sb);
                        //holder.event_reply.setText(eventData.getReplyLastName() + ":" + sb);
                        if ("0".equals(eventData.getUnReadCount()) || "".equals(eventData.getUnReadCount()) || eventData.getUnReadCount() == null) {
                            holder.event_reply_count_layout.setVisibility(View.GONE);
                            holder.event_new_msg.setVisibility(View.GONE);
                        } else {
                            holder.event_reply_count_layout.setVisibility(View.VISIBLE);
                            int unread = Integer.parseInt(eventData.getUnReadCount());
                            holder.event_new_msg.setVisibility(View.VISIBLE);
                            if (unread < 100) {
                                holder.event_reply_count.setText(eventData.getUnReadCount() + "条");
                            } else if (unread >= 100) {
                                holder.event_reply_count.setText("99+条");
                            }
                        }
                    }
                } else if ("6".equals(eventData.getEventType())) {//系统
                    holder.event_img.setImageDrawable(mContext.getResources().getDrawable(R.drawable.system_image));
                }

                break;
            case TYPE_ACTIVITY:
                if ("7".equals(eventData.getEventType())) {//活动
                    holder.event_img.setImageDrawable(mContext.getResources().getDrawable(R.drawable.activity_img));
                }

                holder.event_activity_site.setText(eventData.getActivitySite());
                String time = eventData.getActivityTime();
                if (time != null) {
                    long date = Long.parseLong(time);
                    if (time.length() == 10){
                        date = date * 1000;
                    }
                    holder.event_activity_time.setText(DateUtil.getDetailDate(date));
                }


                break;
            case TYPE_REG:
                if ("9".equals(eventData.getEventType())) {
                    holder.event_img.setImageDrawable(mContext.getResources().getDrawable(R.drawable.reg_img));
                }
                holder.event_activity_site.setText(eventData.getActivitySite());
                String regTime = eventData.getActivityTime();
                if (regTime != null) {
                    long date = Long.parseLong(regTime);
                    if (regTime.length() == 10){
                        date = date * 1000;
                    }
                    holder.event_activity_time.setText(DateUtil.getDetailDate(date));
                }
                if (StringUtil.isEmpty(eventData.getContent1())){
                    holder.event_ll_note.setVisibility(View.GONE);
                }else{
                    holder.event_ll_note.setVisibility(View.VISIBLE);
                }

                break;
            case TYPE_VOTE:
                if ("8".equals(eventData.getEventType())) {
                    holder.event_img.setImageDrawable(mContext.getResources().getDrawable(R.drawable.vote_img));
                }
                if (!StringUtil.isEmpty(eventData.getContent1())){
                    String[] votes = eventData.getContent1().split(",");
                    int length = votes.length;
                    if (length > 5){
                        length = 5;
                    }
                    holder.event_ll_layout.removeAllViews();
                    for (int i = 0;i<length ; i++){
                        TextView tVote = new TextView(mContext);
                        tVote.setText((char)( 65 + i) + ": " + votes[i]);
                        tVote.setTextColor(Color.parseColor("#444444"));
                        // setTextSize() 里面的单位是sp
                        tVote.setTextSize(14);

                        // 父控件是LinearLayout 若是相对布局用RelativeLayout.LayoutParams
                        LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
                                LinearLayout.LayoutParams.WRAP_CONTENT,
                                LinearLayout.LayoutParams.WRAP_CONTENT
                        );
                        // 需要 dp 转成像素单位
                        linearParams.bottomMargin = Constants.dip2px(mContext,8);
                        tVote.setLayoutParams(linearParams);
                        holder.event_ll_layout.addView(tVote);
                    }
                }

                break;
        }

        return convertView;
    }

    private class ViewHolder {
        TextView event_title;
        TextView event_content;
        TextView event_time;
        ImageView event_img;
        ImageView event_new_msg;
        TextView event_reply;
        TextView event_reply_count;
        RelativeLayout event_reply_layout;
        LinearLayout event_reply_count_layout;
        TextView event_activity_time;
        TextView event_activity_site;
        LinearLayout event_ll_layout;
        LinearLayout event_image_layout;
        MyGridView mGvImageGrid;
        LinearLayout event_ll_note;
        TextView event_image_count;


    }

    private static class AnimateFirstDisplayListener extends
            SimpleImageLoadingListener {

        static final List<String> displayedImages = Collections
                .synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    //FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }

    private SpannableStringBuilder handler(final TextView gifTextView, String content) {
        SpannableStringBuilder sb = new SpannableStringBuilder(content);
        String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        while (m.find()) {
            String tempText = m.group();
            try {
                String num = tempText.substring("#[face/png/f_static_".length(), tempText.length() - ".png]#".length());
                String gif = "face/gif/f" + num + ".gif";
                /**
                 * 如果open这里不抛异常说明存在gif，则显示对应的gif
                 * 否则说明gif找不到，则显示png
                 * */
                InputStream is = mContext.getAssets().open(gif);
                sb.setSpan(new AnimatedImageSpan(new AnimatedGifDrawable(is, new AnimatedGifDrawable.UpdateListener() {
                            @Override
                            public void update() {
                                gifTextView.postInvalidate();
                            }
                        })), m.start(), m.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                is.close();
            } catch (Exception e) {
                String png = tempText.substring("#[".length(), tempText.length() - "]#".length());
                try {
                    int resID = mContext.getResources().getIdentifier(png.split("/")[2].substring(0, png.split("/")[2].indexOf(".")), "drawable", mContext.getApplicationInfo().packageName);
                    sb.setSpan(new ImageSpan(mContext, BitmapFactory.decodeResource(mContext.getResources(), resID)), m.start(), m.end(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

//                    sb.setSpan(new ImageSpan(mContext, BitmapFactory.decodeStream(mContext.getAssets().open(png))), m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
//                e.printStackTrace();
            }
        }
        return sb;
    }

}
